package davel

import (
	"fmt"
	"os"
	"sync"
	"time"
)

//日志
type DavelLog struct {
	lock			sync.Mutex
	logDir			string //写入路径
	isSendToFmt		bool //是否输出到控制台
	isSendToFile	bool //是否写入到文件
	isAppendTime	bool //是否添加时间
	fileName		string //当前写入文件名称
	maxLines		int64 //单文件最大写入行数
	writeLines		int64 //已写入行数

	fileHandler		*os.File
}

func NewDavelLog() *DavelLog {
	return &DavelLog{}
}

func(this *DavelLog) Init(logDir string, isSendToFmt bool, isSendToFile bool,isAppendTime bool, maxLines int64) {
	if logDir == "" {
		this.sendToFmt("The log directory path is not provided.")
		return
	}
	this.logDir = logDir
	this.isSendToFmt = isSendToFmt
	this.isSendToFile = isSendToFile
	this.isAppendTime = isAppendTime
	this.maxLines = maxLines
	this.writeLines = 0
	this.changeLogFile()
}

func(this *DavelLog) Gc() {
	if this.fileHandler!=nil {
		this.fileHandler.Close()
	}
}

func(this *DavelLog) Write(msg string) {
	this.lock.Lock()
	defer this.lock.Unlock()

	this.writeLines++
	if this.writeLines > this.maxLines {
		this.changeLogFile()
	}

	msg = this.msgAppend(msg)
	if this.isSendToFmt {
		this.sendToFmt(msg)
	}
	if this.isSendToFile {
		this.sendToFile(msg)
	}
}

//Send logs to the console
func(this *DavelLog) sendToFmt(msg string) {
	fmt.Print(msg)
}

func(this *DavelLog) sendToFile(msg string) {
	if this.fileHandler!=nil {
		this.fileHandler.Write([]byte(msg))
	} else {
		this.sendToFmt("写入日志文件失败" + msg)
	}
}

func (this *DavelLog) getNowTime() string {
	return time.Now().Format("2006/1/2 15:04:05.000000")
}

//格式化错误信息
func(this *DavelLog) msgAppend(msg string) string {
	if this.isAppendTime == true {
		msg = this.getNowTime() + " " + msg
	}
	return msg + "\n"
}

func(this *DavelLog) getLogFile() (string, error) {
	t := time.Now()
	sep := FilePathSep()
	newDir := this.logDir + sep + t.Format("200601")
	err := CreateDir(newDir)
	newSrc := newDir + sep + t.Format("20060102-150405.00") + ".log"
	return newSrc, err
}

func(this *DavelLog) changeLogFile() {
	filename,err := this.getLogFile()
	if(err==nil) {
		if this.fileHandler!=nil {
			defer this.fileHandler.Close()
		}

		this.writeLines = 0
		this.fileName = filename
		fileHandle,err := os.OpenFile(this.fileName, os.O_RDONLY|os.O_CREATE|os.O_APPEND, 0666)
		if err != nil {
			this.sendToFmt("changeLogFile open file error :" + err.Error())
			return
		}
		this.fileHandler = fileHandle
	}
}